<template>
  <div style="width: 100%; height: 100%">
    <ol-map ref="mapRef" style="width: 100%; height: 100%">
      <ol-view ref="view" :center="center" :rotation="rotation" :zoom="zoom" :maxZoom="maxZoom" :projection="projection"
        @change:center="centerChanged" @change:resolution="resolutionChanged" @change:rotation="rotationChanged" />

      <!-- 使用谷歌地图瓦片服务 -->
      <ol-tile-layer>
        <ol-source-xyz :url="`http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}`"
          :attributions="attributions" />
      </ol-tile-layer>

      <!-- 使高德地图瓦片服务 -->
      <!-- <ol-tile-layer>
        <ol-source-xyz :url="`https://webst0{1-4}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}`"
          :attributions="attributions" />
      </ol-tile-layer> -->

      <ol-vector-layer :visible="tubeVisible">
        <ol-source-vector>
          <ol-feature v-for="(item, index) in tubeSourceRef" :key="index"
            :properties="{ id: item.id, properties: item }">

            <ol-geom-multi-line-string :coordinates="item.geometry" />

            <ol-style>
              <!-- 动态管道颜色 -->
              <ol-style-stroke :color="getRiskColor(item.risk)" :width="tubeWidth" />

              <!-- 管道名称的文本样式 -->
              <ol-style-text v-if="tubeTextVisible" :text="item.pipeName" :offsetY="18" :font="'16px 黑体,sans-serif'"
                :fill="[3, 5, 3]" placement="line" textAlign="center" textBaseline="middle" />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-vector-layer :visible="wellVisible">
        <ol-source-vector>
          <!-- 使用 v-for 遍历 wellSourceRef 数据，并通过 ol-geom-point 组件将每个油水井的坐标渲染到地图上。-->
          <ol-feature v-for="(item, index) in wellSourceRef" :key="index"
            :properties="{ id: item.id, properties: item }">
            <ol-geom-point :coordinates="item.location" />

            <ol-style>
              <!-- 油水井颜色 -->
              <ol-style-circle :radius="wellRadius">
                <ol-style-fill color="#ff0000" />
                <ol-style-stroke :width="wellStrokeWidth" color="#ff0000" />
              </ol-style-circle>
              <!-- 油水井名称的文本样式 -->
              <ol-style-text :text="item.wellName" :offsetY="18" :font="'16px 黑体,sans-serif'" :fill="[3, 5, 3]" />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-vector-layer :visible="stationVisible">
        <ol-source-vector>
          <!-- 使用 v-for 遍历 meteringStationSourceRef 数据渲染到地图上。-->
          <ol-feature v-for="(item, index) in meteringStationSourceRef" :key="index"
            :properties="{ id: item.id, properties: item }">
            <ol-geom-point :coordinates="item.location" />
            <ol-style>
              <ol-style-icon :scale="stationScale" :src="PngJiLiangZhan" />
              <ol-style-text :text="item.stationName" :offsetY="30" :font="'15px 黑体,sans-serif'" />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-vector-layer :visible="stationVisible">
        <ol-source-vector>
          <!-- 使用 v-for 遍历 valveSourceRef 数据渲染到地图上。-->
          <ol-feature v-for="(item, index) in valveSourceRef" :key="index"
            :properties="{ id: item.id, properties: item }">
            <ol-geom-point :coordinates="item.location" />
            <ol-style>
              <ol-style-icon :scale="stationScale" :src="PngFachi" />
              <ol-style-text :text="item.poolName" :offsetY="34" :font="'15px 黑体,sans-serif'" />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-vector-layer :visible="stationVisible">
        <ol-source-vector>
          <!-- 使用 v-for 遍历 transferStationSourceRef 数据渲染到地图上。-->
          <ol-feature v-for="(item, index) in transferStationSourceRef" :key="index"
            :properties="{ id: item.id, properties: item }">
            <ol-geom-point :coordinates="item.location" />
            <ol-style>
              <ol-style-icon :scale="stationScale" :src="PngZhuanyouzhan" />
              <ol-style-text :text="item.stationName" :offsetY="20" :font="'15px 黑体,sans-serif'" />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-rotate-control></ol-rotate-control>
      <ol-fullscreen-control></ol-fullscreen-control>
      <ol-mouseposition-control />
    </ol-map>
    <TModal />
    <WModal />
    <MSModal />
    <VEModal />
    <TRModal />
  </div>
</template>

<script setup lang="ts">
import { watch, onMounted, ref, onBeforeMount } from 'vue';
import Map from 'ol/Map';

import type { FeatureLike } from 'ol/Feature';

import { useVbenModal } from '@vben/common-ui';
import TubeModal from './modal/tubeModal.vue';
import WellModal from './modal/wellModal.vue';
import MeasuringStationModal from './modal/measuringStationModal.vue';
import ValveModal from './modal/valveModal.vue';
import TransferStationModal from './modal/transferStationModal.vue';


import PngJiLiangZhan from '#/assets/gis/计量站.png';
import PngFachi from '#/assets/gis/油集输管线阀池L.png';
import PngZhuanyouzhan from '#/assets/gis/转油站.png';

import { getMeteringStationsByGis, getWellsByGis, getPipesByGis, getValvesByGis, getTransferStationsBygis } from '#/api/gis';

const attributions =
  '© <a href="https://www.ckxgzxa.top"  target="_blank"><bold>CKXGZXA</bold></a> 版权所有.';
const center = ref([86.066, 46.151]);
const projection = ref('EPSG:4326');
const zoom = ref(17);
const maxZoom = ref(19);
const rotation = ref(0);

const currentCenter = ref(center.value);
const currentZoom = ref(zoom.value);
const currentRotation = ref(rotation.value);
const currentResolution = ref(0);

//站库的相关 
const valveSourceRef = ref();
const meteringStationSourceRef = ref();
const transferStationSourceRef = ref();
const stationVisible = ref(false);
const stationScale = ref(1);

//管道相关 
const tubeSourceRef = ref();
const tubeVisible = ref(true);
const tubeWidth = ref(3);
const tubeTextVisible = ref(false);

//油井相关 
const wellSourceRef = ref();
const wellStrokeWidth = ref(0);
const wellRadius = ref(0);
const wellVisible = ref(false);



watch(currentZoom, (zoom) => {
  if (zoom >= 17) {
    tubeTextVisible.value = true;
  } else {
    tubeTextVisible.value = false;
  }

  if (zoom < 16) {
    wellVisible.value = false;
    stationVisible.value = false;
  } else {
    // 随zoom线性增长, 速率越来越慢 
    wellVisible.value = true;
    stationVisible.value = true;

    wellStrokeWidth.value = 5 * (zoom - 15) + 1;
    tubeWidth.value = zoom * 0.3;
    stationScale.value = zoom * 0.03;
  }
});

const mapRef = ref<{ map: Map }>();

function resolutionChanged(event: {
  target: { getResolution: () => number; getZoom: () => number };
}) {
  currentResolution.value = event.target.getResolution();
  currentZoom.value = event.target.getZoom();
}
function centerChanged(event: { target: { getCenter: () => number[] } }) {
  currentCenter.value = event.target.getCenter();
}
function rotationChanged(event: { target: { getRotation: () => number } }) {
  currentRotation.value = event.target.getRotation();
}

const [TModal, TModalApi] = useVbenModal({
  connectedComponent: TubeModal,
  title: 'Tube Modal',
});

const [WModal, WModalApi] = useVbenModal({
  connectedComponent: WellModal,
  title: 'Well Modal',
});

const [MSModal, MSModalApi] = useVbenModal({
  connectedComponent: MeasuringStationModal,
  title: 'Measuring Station Modal',
});

const [VEModal, VEModalApi] = useVbenModal({
  connectedComponent: ValveModal,
  title: 'Valve Modal',
});

const [TRModal, TRModalApi] = useVbenModal({
  connectedComponent: TransferStationModal,
  title: 'TransferStation Modal',
});

// 定义风险等级类型
type RiskLevel = '良好' | '较好' | '一般' | '较危险' | '危险';

// 颜色映射表
const riskColorMap: Record<RiskLevel, string> = {
  '良好': '#00ff00',    // 亮绿色 
  '较好': '#4CAF50',   // 柔和绿 
  '一般': '#000000',    // 黑色 
  '较危险': '#FF5722',  // 橙红色 
  '危险': '#FF0000'     // 正红色 
};

// 颜色计算方法 
const getRiskColor = (riskLevel: any): string => {
  if (typeof riskLevel !== 'string') {
    console.warn('非法等级:', riskLevel);
    return '#000000'; // 默认黑色
  }

  // 确保 riskLevel 是合法键
  return riskColorMap[riskLevel as RiskLevel] || '#000000'; // 默认黑色
};


function openTubeModal(data: any) {
  TModalApi.setState({
    title: data.pipeName,
    draggable: true,
  });
  TModalApi.setData(data);
  TModalApi.open();
}

function openWellModal(data: any) {
  console.log('data:', data);
  WModalApi.setState({
    title: data.wellName,
    draggable: true,
  });
  WModalApi.setData(data);
  WModalApi.open();
}

function openMeasuringStationModal(data: any) {
  MSModalApi.setState({
    title: data.stationName,
    draggable: true,
  });
  MSModalApi.setData(data);
  MSModalApi.open();
}

function openValveModal(data: any) {
  VEModalApi.setState({
    title: data.poolName,
    draggable: true,
  });
  VEModalApi.setData(data);
  VEModalApi.open();
}

function openTransferStationModal(data: any) {
  TRModalApi.setState({
    title: data.stationName,
    draggable: true,
  });
  TRModalApi.setData(data);
  TRModalApi.open();
}

async function fetchData() {
  try {
    // 获取集输数据 
    var res = await getPipesByGis();
    tubeSourceRef.value = res;


    // 获取生产井数据 
    res = await getWellsByGis();
    wellSourceRef.value = res.items;

    // 获取计量间数据 
    res = await getMeteringStationsByGis();
    meteringStationSourceRef.value = res;

    //获取阀门数据 
    res = await getValvesByGis();
    valveSourceRef.value = res;
    //console.log('valveSourceRef',  valveSourceRef.value);  

    //获取转油站数据 
    res = await getTransferStationsBygis();
    transferStationSourceRef.value = res;
    console.log('transferStationSourceRef', transferStationSourceRef.value);

  } catch (error) {
    // 捕获并处理错误 
    console.error(" 错误获取数据:", error);
  }
}

onBeforeMount(() => {
  fetchData();
});

onMounted(() => {
  const map: Map = mapRef.value?.map!;
  map.on('click', (event) => {
    // 打印出当前位置要素信息 
    map.forEachFeatureAtPixel(event.pixel, (feature: FeatureLike) => {
      //console.log("feature.getProperties().properties.wellName:",  feature.getProperties().properties.wellName);  
      const properties = feature.getProperties().properties;
      if (properties.wellName) {
        openWellModal(properties);
      } else if (properties.pipeName) {
        openTubeModal(properties);
      } else if (properties.stationName) {
        if (properties.capacity) {
          openMeasuringStationModal(properties);
        } else {
          openTransferStationModal(properties);
        }

      } else if (properties.poolName) {
        openValveModal(properties);
      } else {
        // 如果没有匹配的属性，可以选择记录日志或执行其他操作 
        console.log(" 未知要素类型:", properties);
      }
    });
  });
}); 
</script>
